<template>
    <v-dialog v-model="dialogFormVisible" max-width="800px" persistent scrollable>
        <v-card class="elevation-10 pa-2">
            <v-card-title class="d-flex align-center"> 
                {{ title }}
            </v-card-title>

            <v-card-text>
                <v-form ref="formRef" v-model="formValid">
                    <v-row>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.statusCode"
                                :rules="rules.statusCode"
                                density="compact"
                                hide-details="auto"
                                label="状态编码"
                                required
                                variant="outlined"
                                :disabled="form.statusType === 'CORE'"
                                placeholder="如：10, 11, 12"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.statusName"
                                :rules="rules.statusName"
                                density="compact"
                                hide-details="auto"
                                label="状态名称"
                                required
                                variant="outlined"
                                placeholder="如：试听中, 已报名"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-select
                                v-model="form.statusType"
                                :items="statusTypeOptions"
                                :rules="rules.statusType"
                                density="compact"
                                hide-details="auto"
                                label="状态类型"
                                required
                                variant="outlined"
                                :disabled="form.statusType === 'CORE'"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-select
                                v-model="form.parentType"
                                :items="parentTypeOptions"
                                :rules="rules.parentType"
                                density="compact"
                                hide-details="auto"
                                label="父级状态类型"
                                required
                                variant="outlined"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-select
                                v-model="form.statusColor"
                                :items="colorOptions"
                                density="compact"
                                hide-details="auto"
                                label="状态颜色"
                                variant="outlined"
                            >
                                <template #item="{ props, item }">
                                    <v-list-item v-bind="props">
                                        <template #prepend>
                                            <v-chip :color="item.value" size="small">
                                                {{ item.title }}
                                            </v-chip>
                                        </template>
                                    </v-list-item>
                                </template>
                                <template #selection="{ item }">
                                    <v-chip :color="item.value" size="small">
                                        {{ item.title }}
                                    </v-chip>
                                </template>
                            </v-select>
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model.number="form.sortOrder"
                                density="compact"
                                hide-details="auto"
                                label="排序号"
                                type="number"
                                variant="outlined"
                                placeholder="数字越小排序越前"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-switch
                                :model-value="form.isActive === 1"
                                @update:model-value="(val: boolean) => form.isActive = val ? 1 : 0"
                                color="primary"
                                hide-details
                                label="是否启用"
                                :disabled="form.statusType === 'CORE'"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-switch
                                :model-value="form.isSystem === 1"
                                @update:model-value="(val: boolean) => form.isSystem = val ? 1 : 0"
                                color="primary"
                                hide-details
                                label="是否系统内置"
                                disabled
                            />
                        </v-col>
                        <v-col cols="12">
                            <v-textarea
                                v-model="form.remark"
                                density="compact"
                                hide-details="auto"
                                label="备注"
                                variant="outlined"
                                rows="3"
                                placeholder="状态说明或使用场景"
                            />
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer />
                <v-btn color="grey-darken-1" variant="text" @click="close"> 取消 </v-btn>
                <v-btn :loading="saving" color="primary" variant="text" @click="save"> 确定 </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted } from 'vue';
import { doInsert, doUpdate, type TenantCustomerStatusModel, type ApiResponse } from '@/api/tenant/customerstatus/TenantCustomerStatusManagementApi';
import { isNull } from '@/utils/validate';
import { formateDate } from '@/utils/format';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const dialogFormVisible = ref(false);
const title = ref('');
const formValid = ref(false);
const formRef = ref();
const saving = ref(false);
const defaultFrom: TenantCustomerStatusModel = {
    statusCode: '',
    statusName: '',
    statusType: 'CUSTOM',
    parentType: 'NORMAL',
    statusColor: 'primary',
    sortOrder: 0,
    isSystem: 0,
    isActive: 1,
    remark: ''
};

// 表单数据
const form = reactive<Partial<TenantCustomerStatusModel>>(structuredClone(defaultFrom));

// 选项数据
const statusTypeOptions = [
    { title: '核心状态', value: 'CORE' },
    { title: '自定义状态', value: 'CUSTOM' }
];

const parentTypeOptions = [
    { title: '正常', value: 'NORMAL' },
    { title: '流失', value: 'LOST' }
];

const colorOptions = [
    { title: '主要', value: 'primary' },
    { title: '成功', value: 'success' },
    { title: '信息', value: 'info' },
    { title: '警告', value: 'warning' },
    { title: '错误', value: 'error' },
    { title: '次要', value: 'secondary' }
];

// 验证规则
const rules = {
    statusCode: [
        (v: any) => !!v || '状态编码不能为空',
        (v: any) => /^\d+$/.test(v) || '状态编码必须是数字'
    ],
    statusName: [(v: any) => !!v || '状态名称不能为空'],
    statusType: [(v: any) => !!v || '状态类型不能为空'],
    parentType: [(v: any) => !!v || '父级状态类型不能为空']
};

// 事件发射
const emit = defineEmits<{
    fetchData: [];
}>();

// 显示编辑对话框
function showEdit(row?: TenantCustomerStatusModel) {
    if (!row) {
        title.value = '添加客户状态';
        // 重置表单为默认值
        Object.assign(form, structuredClone(defaultFrom));
    } else {
        title.value = '编辑客户状态';
        // 复制行数据到表单
        const formData = { ...row };
        Object.assign(form, formData);
    }

    dialogFormVisible.value = true;
}

// 关闭对话框
function close() {
    dialogFormVisible.value = false;
    nextTick(() => {
        if (formRef.value) {
            formRef.value.reset();
        }
        // 重置表单数据
        Object.assign(form, structuredClone(defaultFrom));
    });
}

// 保存
async function save() {
    if (!formRef.value) return;

    try {
        const { valid } = await formRef.value.validate();
        if (!valid) return;

        saving.value = true;

        // 处理表单数据
        const submitData = { ...form } as TenantCustomerStatusModel;
        handlerFormData(submitData);

        let response: ApiResponse<TenantCustomerStatusModel>;

        // 编辑模式
        if (!isNull(submitData.id)) {
            let { msg } = await doUpdate(submitData);
            showSuccess(msg || '更新成功');
        } else {
            // 新增模式
            let { msg } = await doInsert(submitData);
            showSuccess(msg || '添加成功');
        }

        // 通知父组件刷新数据
        emit('fetchData');
        close();
    } catch (error) {
        console.error('保存失败:', error);
        showError('保存失败');
    } finally {
        saving.value = false;
    }
}

// 处理表单数据
function handlerFormData(formData: any) {
    if (!isNull(formData)) {
        for (const key in formData) {
            // 对于时间类进行处理
            if (Object.prototype.toString.call(formData[key]) === '[object Date]') {
                formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
            }
            // 处理datetime-local格式
            else if (typeof formData[key] === 'string' && formData[key].includes('T')) {
                formData[key] = formData[key].replace('T', ' ') + ':00';
            }
        }
    }
}

// 暴露方法
defineExpose({
    showEdit
});

// 生命周期
onMounted(() => {
    // 初始化
});
</script>

<style lang="scss" scoped>
:deep(.v-dialog) {
    .v-card-title {
        background-color: rgb(var(--v-theme-primary));
        color: white;
    }
}
</style> 